package com.xiaoqi.reggie.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoqi.reggie.dto.DishDto;
import com.xiaoqi.reggie.entity.Dish;
import com.xiaoqi.reggie.entity.DishFlavor;
import com.xiaoqi.reggie.service.DishFlavorService;
import com.xiaoqi.reggie.service.DishService;
import com.xiaoqi.reggie.mapper.DishMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
* @author xiaoqi
* @description 针对表【dish(菜品管理)】的数据库操作Service实现
* @createDate 2022-09-19 15:53:48
*/
@Service
@Transactional
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish>
implements DishService{
    @Autowired
    DishFlavorService dishFlavorService;
    @Override
    public void saveWithFlavor(DishDto dishDto) {
        //先向dish表中保存字段属性
        super.save(dishDto);
        //取出dishDto中的list数据，给里面的元素（dishFlavor）赋上dishId
        Long id = dishDto.getId();
        List<DishFlavor> flavors = dishDto.getFlavors();
        for(DishFlavor dishFlavor:flavors){
            dishFlavor.setDishId(id);
        }
        //将这个集合批量保存在dishFlavor中
        dishFlavorService.saveBatch(flavors);
    }

    @Override
    public DishDto getByIdWithFlavor(Long id) {
        //先根据id查询出dish
        Dish dish = this.getById(id);
        DishDto dishDto=new DishDto();
        //拷贝到dishDto中
        BeanUtils.copyProperties(dish,dishDto);
        //根据dishId,在dishFlavor中查找数据并且赋值在dishDto中
        LambdaQueryWrapper<DishFlavor>queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,id);
        List<DishFlavor> list = dishFlavorService.list(queryWrapper);
        dishDto.setFlavors(list);
        return dishDto;
    }

    @Override
    public void updateWithFlavor(DishDto dishDto) {
        //先在dish表中保存dishDto在该表中含有的字段
        this.updateById(dishDto);
        //在dishFlavor表中先删除该菜品的口味信息
        LambdaQueryWrapper<DishFlavor>queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(queryWrapper);
        //在dishFlavor中增加该菜品有关口味
        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor dishFlavor:flavors){
            //在每个dishFlavor对象中都添加dishId
            dishFlavor.setDishId(dishDto.getId());
        }
        dishFlavorService.saveBatch(flavors);
    }

}
